package com.wowotou.rabbitmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable("message") String message) {
        log.info("当前时间：{}，发送消息给ttl队列：{}", new Date().toString(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列：" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列：" + message);
    }

    @GetMapping("/sendExpirationMessage/{message}/{ttlTime}")
    public void sendExpirationMessage(@PathVariable("message") String message, @PathVariable("ttlTime") String ttlTime) {
        log.info("当前时间：{}，发送消息时长为{}的消息：{} 给QC队列：", new Date().toString(), ttlTime, message);
        rabbitTemplate.convertAndSend("X", "XC", "消息的ttl为" + ttlTime + "s，内容为：" + message, msg -> {
            //设置过期时间为 ttl,注意单位为 ms 哦
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }

    @GetMapping("/sendDelayedMessage/{message}/{ttlTime}")
    public void sendDelayedMessage(@PathVariable("message") String message, @PathVariable("ttlTime") Integer ttlTime) {
        log.info("当前时间：{}，发送消息时长为{}的延迟消息：{} 给延迟队列队列：", new Date().toString(), ttlTime, message);
        rabbitTemplate.convertAndSend("delayed.exchange", "delayed.routingkey", "消息的ttl为" + ttlTime + "s，内容为：" + message, msg -> {
            //设置延迟时间为 ttl,注意单位为 ms 哦
            msg.getMessageProperties().setDelay(ttlTime);
            return msg;
        });
    }

    @GetMapping("/sendPriorityMessage")
    public void sendPriorityMessage() {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int priority = random.nextInt(10);
            rabbitTemplate.convertAndSend("X", "priorityKey", "消息的优先级为"+priority, msg -> {
                //设置延迟时间为 ttl,注意单位为 ms 哦
                msg.getMessageProperties().setPriority(priority);
                return msg;
            });
        }
    }
}
